Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
Best way to ensure multiple states are updated and call a function once all states updated [React Functional component]

In my use case there are some controlled input components that stores data in states. When I change one of the dropdown input, it changes 3 more states and triggers an API call. How can I ensure that the 3 states are updated before making the API call ? I am using react functional component.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Option 1

If you're using React 18 and you call those 3 setState(...) within the same function, those states are guaranteed to be updated in the next re-render thanks to automatic batching.

So in this case you can just use an useEffect on any of these 3 states, and call the API in that effect. Check this sandbox for a simple example.

Option 2

For people using React 17 or earlier, you still got auto batching, but only inside React event handlers (please refer to this awesome answer). If you're updating states outside React event handlers, the easiest way is, instead of useState three times, you just put those states in a single state in the first place to make sure they will be updated at the same time, because they are in the same state.

For example:

const [state, setState] = useState({
  state0: 0,
  state1: 'a',
  state2: true,
})

useEffect(() => {
  // Call API here
}, [state])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!